package com.moon.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * 图片加载
 * 
 * @author paul
 * @date 2014年5月11日
 */
public class ImageLoadUtils {
    private static final String TAG = ImageLoadUtils.class.getSimpleName();

    public static Bitmap getBitmapFromUrl(String url) {
        if(StringUtils.isBlank(url)){
            return null;
        }
        //把一个url的网络图片变成一个本地的BitMap
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    
    
    /** 保存方法 */
    public static String saveBitmap(Bitmap bm,String fileName) {
        if(bm == null){
            return null;
        }
        File filePath = new File(Environment.getExternalStorageDirectory().getPath()+"/moon/");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        
        File f = new File(Environment.getExternalStorageDirectory().getPath()+"/moon/", fileName+".jpeg");
        if (f.exists()) {
            f.delete();
        }

        try {
            
            FileOutputStream out = new FileOutputStream(f);
            //Bitmap bm1 = ImageCompressUtils.comp(bm, Bitmap.CompressFormat.JPEG, 10);
            bm.compress(Bitmap.CompressFormat.JPEG, 50, out);
            out.flush();
            out.close();
            return f.getPath();
        } catch (Exception e) {
            Log.e(TAG, "saveBitmap error,", e);
            return null;
        }
    }
}
